<template>
    <div>
        <van-field label="发送验证码" center clearable placeholder="请输入短信验证码" type="number" v-model="code">
            <van-button class="bg-theme-color verify-code" @click.native="sendCode(tel, type)"
                        slot="button" size="small" :class="{'verify-code-active':timer !== 0}">
                {{timer?timer:'发送验证码'}}
            </van-button>
        </van-field>
    </div>
</template>
<script>

    import {mapGetters} from "vuex";
    import * as constApi from "../utils/constApi"
    import http from "../utils/http"

    export default {
        data() {
            return {
                timer: 0,
                dark: false,
                code: ''
            };
        },

        props: ["tel", "type"],
        watch: {
            code: function (val) {
                this.$emit('codeValue', val)

            }
        },
        methods: {
            sendCode() {
                let tel = /^[1]{1}[3,5,7,8,9]{1}[0-9]{9}$/;
                if (!tel.test(this.tel)) {
                    this.fail('请输入正确的手机号码')
                    return;
                }
                http.post(constApi.GET_PHONE_CODE, {phone: this.tel, user_type: this.type}).then((res) => {
                    if (res.data.code !== 0) return this.fail(res.data.msg);
                    this.timer = 60;
                    this.countDown();
                });
            },

            //计时
            countDown() {
                if (this.timer <= 0) return true;
                setTimeout(() => {
                    this.timer--;
                    this.countDown();
                }, 1000);
            }
        }
    };
</script>
<style scoped>
    .verify-code {
        color: #fff;
    }

    .verify-code-active {
        padding: 0;
        background: #fff;
        border: 0;
    }
</style>


